<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Assignment;
use App\Http\Requests;

use DB;

class AssignmentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $lists = DB::table('assignment')
            ->paginate(self::PER_PAGE);

        $pagination = $this->pagination($lists);

        return view('admin.assignments.index')
            ->with([
                'lists' => $lists,
                'pagination' => $pagination,
            ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.assignments.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|unique:assignment|max:255',
        ]);

        $assignment = new Assignment;

        $assignment->title = $request->title;

        $assignment->save();

        return redirect('b/assignments');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $assignment = DB::table('assignment')
            ->find($id);

        return view('admin.assignments.edit')
            ->withId($id)
            ->with('assignment', $assignment);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'title' => 'required|unique:assignment,title,'.$id.'|max:255',
        ]);

        $assignment = Assignment::find($id);

        $assignment->title = $request->title;

        $assignment->save();

        return redirect('b/assignments');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $flag = Assignment::destroy($id);

        if ($flag) {
            // delete successful
            return ['error' => false];
        }

        return [
            'error' => true,
            'error_description' => '删除失败。',
        ];
    }
}
